package com.maxd.controller.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.maxd.adapter.IgnoreSecurity;
import com.maxd.error.ExceptionEnum;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.*;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.token.TokenJpaRepository;
import com.maxd.respository.token.TokenRepository;
import com.maxd.respository.userinfo.UserJpaRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.respository.word.WordJpaRepository;
import com.maxd.respository.word.WordRepository;
import com.maxd.service.message.IMessageService;
import com.maxd.service.userinfo.IUserService;
import com.maxd.service.wx.AccountService;
import com.maxd.service.wx.AccountTokenService;
import com.maxd.utils.*;
import com.pdd.pop.ext.apache.http.client.config.RequestConfig;
import com.pdd.pop.ext.apache.http.client.methods.HttpGet;
import com.pdd.pop.sdk.common.util.JsonUtil;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.pop.request.PddDdkGoodsDetailRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddDdkGoodsSearchRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddDdkGoodsZsUnitUrlGenRequest;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkGoodsDetailResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkGoodsSearchResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkGoodsZsUnitUrlGenResponse;
import com.qq.weixin.mp.aes.AesException;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import weixin.popular.api.MenuAPI;
import weixin.popular.api.MessageAPI;
import weixin.popular.api.UserAPI;
import weixin.popular.bean.BaseResult;
import weixin.popular.bean.message.EventMessage;
import weixin.popular.bean.user.FollowResult;
import weixin.popular.bean.user.User;
import weixin.popular.bean.xmlmessage.XMLMessage;
import weixin.popular.bean.xmlmessage.XMLTextMessage;
import weixin.popular.support.ExpireKey;
import weixin.popular.support.expirekey.DefaultExpireKey;
import weixin.popular.util.SignatureUtil;
import weixin.popular.util.StreamUtils;
import weixin.popular.util.XMLConverUtil;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zhangd
 */
@Slf4j
@RestController
@Api(value = "微信账号管理", tags = {"微信账号管理"})
@RequestMapping("/wx")
public class WxController {
    private Logger logger = LoggerFactory.getLogger(WxController.class);
    private int number = 1;
    /**
     * 定义 AccountService
     */
    private final AccountService accountService;
    private final AccountTokenService accountTokenService;
    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private WordRepository wordRepository;
    @Autowired
    private WordJpaRepository wordJpaRepository;
    @Autowired
    private UserJpaRepository userJpaRepository;
    @Autowired
    private TokenRepository tokenRepository;
    @Autowired
    private TokenJpaRepository tokenJpaRepository;
    @Autowired
    private IMessageService iMessageService;
    //重复通知过滤
    private static ExpireKey expireKey = new DefaultExpireKey();

    /**
     * 构造方法
     *
     * @param accountService AccountService
     */
    @Autowired
    public WxController(AccountService accountService, AccountTokenService accountTokenService) {
        this.accountService = accountService;
        this.accountTokenService = accountTokenService;
    }

    /**
     * 根据微信获取凭证
     *
     * @param openId 微信
     * @return BingingResultView
     */
    @PostMapping("/account/token/{openId}")
    @ApiOperation("获取token")
    public String getAccountTokenWeixin(@PathVariable("openId") String openId) {
        return accountService.getAccountTokenWeixin(openId);
    }

    @RequestMapping(value = "/saveWord", method = RequestMethod.POST)
    @ApiOperation("保存关键字")
    public Result saveWord(@RequestBody WordInfo wordInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        wordInfo.setCreateAt(sdf.format(now));
        return ResultUtil.success(wordJpaRepository.save(wordInfo));
    }

    @PostMapping("/getWordList")
    @ApiOperation("保存关键字")
    public Result getWordList() {
        return ResultUtil.success(wordJpaRepository.findAll());
    }

    @PostMapping("/deleteById/{id}")
    @ApiOperation("删除关键字")
    public Result deleteById(@PathVariable Long id) {
        wordJpaRepository.deleteById(id);
        return ResultUtil.success();
    }

    /**
     * 获取openid
     *
     * @param code 微信code
     * @return openid
     */
    @GetMapping("/openId/{code:.+}")
    @ApiOperation("根据code获取openid")
    public String getOpenid(@PathVariable("code") String code) {
        return accountService.getOpenId(code);
    }

    @GetMapping("/createQr")
    @ApiOperation("用户端创建公众号免单商品二维码")
    public Result createQr(@RequestParam String relation) {
        return accountService.createQr(relation);
    }

    @ApiOperation("微信小程序登陆")
    @RequestMapping(value = "/mp/login", method = RequestMethod.GET)
    public Result user_login(String code) {
        try {
            String appid = commonRepository.findOne(45).getValue();
            String secret = commonRepository.findOne(46).getValue();
            // 配置请求参数
            Map<String, String> param = new HashMap<>();
            param.put("appid", appid);
            param.put("secret", secret);
            param.put("js_code", code);
            param.put("grant_type", "authorization_code");
            param.put("scope", "snsapi_userinfo");
            // 发送请求
            String wxResult = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", param);
            System.err.println(wxResult);
            JSONObject jsonObject = JSONObject.parseObject(wxResult);
            System.err.println(jsonObject);
            // 获取参数返回的
            Map<String, String> map = new HashMap<>();
            String session_key = jsonObject.get("session_key").toString();
            String open_id = jsonObject.get("openid").toString();
            if (jsonObject.get("unionid") != null) {
                String unionid = jsonObject.get("unionid").toString();
                map.put("unionid", unionid);
            } else {
                map.put("unionid", "-1");
            }
            CommonInfo one = commonRepository.findOne(248);
            if ("是".equals(one.getValue())) {
                UserInfo userByWxId = userRepository.getUserByMpId(open_id);
                if (userByWxId != null && StringUtils.isNotEmpty(userByWxId.getPhone())) {
                    map.put("flag", "0");
                } else {
                    map.put("flag", "1");
                }
            } else {
                map.put("flag", "0");
            }
            // 封装返回小程序
            map.put("session_key", session_key);
            map.put("open_id", open_id);
            return ResultUtil.success(map);
        } catch (Exception e) {
//            log.error(e.toString());
            return ResultUtil.error(-1, "登录失败！");
        }
    }

    @ApiOperation("解密手机号")
    @RequestMapping(value = "/selectPhone", method = RequestMethod.POST)
    public Result getPhoneNumberBeanS5(@RequestBody WxPhone wxPhone) {
        return UserConstantInterface.decryptS5(wxPhone.getDecryptData(), wxPhone.getKey(), wxPhone.getIv());
    }


    private Result getResult(UserInfo userInfo) {
        Token byUserIds = tokenRepository.findByUserId(String.valueOf(userInfo.getId()));
        if (byUserIds == null) {
            String uuid = UUID.randomUUID().toString();
            Token token = new Token();
            token.setUserId(String.valueOf(userInfo.getId()));
            token.setUuid(uuid);
            Token save = tokenJpaRepository.save(token);
            return ResultUtil.success(save);
        }
        return ResultUtil.success(byUserIds);
    }

    /*@GetMapping("/mpCreateQr")
    @ApiOperation("小程序创建二维码")
    public Result mpCreateQr(@RequestParam String value) {
        return accountService.createQr(value);
    }*/

    @GetMapping("/mpCreateGoodsQr")
    @ApiOperation("小程序商品二维码")
    @IgnoreSecurity
    public void mpCreateGoodsQr(@RequestParam String relation, @RequestParam String goodsId, @RequestParam String type, String page, HttpServletResponse response) {
        SenInfoCheckUtil.getImg(relation, goodsId, type, page, response);
    }

    @GetMapping("/mpCreateQr")
    @ApiOperation("小程序推广二维码")
    @IgnoreSecurity
    public void mpCreateQr(@RequestParam String relation, HttpServletResponse response) {
        SenInfoCheckUtil.getPoster(relation, response);
    }


    @RequestMapping(value = "/sqx/sendMsg", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation("回复公众号消息")
    @ResponseBody
    public Result sendMsg(String content, Long id, HttpServletResponse response) throws IOException {
        MessageInfo messageInfo = iMessageService.selectById(id);
        ServletOutputStream outputStream = response.getOutputStream();
        WXBizMsgCrypt wxBizMsgCrypt = (WXBizMsgCrypt) JSON.parse(messageInfo.getWxBizMsgCrypt());
        //创建回复
        XMLMessage xmlTextMessage = new XMLTextMessage(
                messageInfo.getFromUserName(),
                messageInfo.getToUserName(),
                content);
        //回复
        xmlTextMessage.outputStreamWrite(outputStream, wxBizMsgCrypt);
        return ResultUtil.success();
    }


    /**
     * 微信公众号消息管理
     *
     * @return openid
     */
    @RequestMapping(value = "/sqx/connect", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation("在公众号平台配置 微信公众号消息")
    @ResponseBody
    public void connectWeixinsqx(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //公众号Token
        CommonInfo token = commonRepository.findOne(16);
        //公众号EncodingAESKey
        CommonInfo EncodingAESKey = commonRepository.findOne(17);
        //微信APPID
        CommonInfo appid = commonRepository.findOne(5);
        //后台服务域名配置
        CommonInfo yuming = commonRepository.findOne(19);
        //邀请码
        CommonInfo one = commonRepository.findOne(4);
        //后台服务名称
        CommonInfo name = commonRepository.findOne(12);
        ServletInputStream inputStream = request.getInputStream();
        ServletOutputStream outputStream = response.getOutputStream();
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        //加密模式
        String encrypt_type = request.getParameter("encrypt_type");
        String msg_signature = request.getParameter("msg_signature");
        WXBizMsgCrypt wxBizMsgCrypt = null;
        //加密方式
        boolean isAes = "aes".equals(encrypt_type);
        if (isAes) {
            try {
                wxBizMsgCrypt = new WXBizMsgCrypt(accountTokenService.getWxToken(), EncodingAESKey.getValue() != null ? EncodingAESKey.getValue() : Config.encodingAesKey, appid.getValue() != null ? appid.getValue() : Config.appId);
            } catch (AesException e) {
                e.printStackTrace();
            }
        }

        //首次请求申请验证,返回echostr
        if (isAes && echostr != null) {
            try {
                echostr = URLDecoder.decode(echostr, "utf-8");
                assert wxBizMsgCrypt != null;
                String echostr_decrypt = wxBizMsgCrypt.verifyUrl(msg_signature, timestamp, nonce, echostr);
                outputStreamWrite(outputStream, echostr_decrypt);
                return;
            } catch (AesException e) {
                e.printStackTrace();
            }
        } else if (echostr != null) {
            outputStreamWrite(outputStream, echostr);
            return;
        }

        EventMessage eventMessage = null;
        if (isAes) {
            try {
                //获取XML数据（含加密参数）
                String postData = StreamUtils.copyToString(inputStream, Charset.forName("utf-8"));
                //解密XML 数据
                assert wxBizMsgCrypt != null;
                String xmlData = wxBizMsgCrypt.decryptMsg(msg_signature, timestamp, nonce, postData);
                //XML 转换为bean 对象
                eventMessage = XMLConverUtil.convertToObject(EventMessage.class, xmlData);
            } catch (AesException e) {
                e.printStackTrace();
            }
        } else {
            if (signature == null) {
                System.out.println("The request signature is null");
                return;
            }
            //验证请求签名
            if (!signature.equals(SignatureUtil.generateEventMessageSignature(token.getValue() != null ? token.getValue() : Config.token, timestamp, nonce))) {
                System.out.println("The request signature is invalid");
                return;
            }

            if (inputStream != null) {
                //XML 转换为bean 对象
                eventMessage = XMLConverUtil.convertToObject(EventMessage.class, inputStream);
            }
        }

        String fromUserName = eventMessage.getFromUserName();
        String key = fromUserName + "__"
                + eventMessage.getToUserName() + "__"
                + eventMessage.getMsgId() + "__"
                + eventMessage.getCreateTime();
        if (expireKey.exists(key)) {
            //重复通知不作处理
            return;
        } else {
            expireKey.add(key);
        }

        String event = eventMessage.getEvent();
        String msgType1 = eventMessage.getMsgType();
        String eventKey = eventMessage.getEventKey();
        logger.error("getEvent----" + event);
        logger.error("getMsgType----" + msgType1);
        logger.error("eventKey----" + eventKey);
        //判断请求是否事件类型 event 用户关注公众号事件
        if (MessageUtil.EVENT_SUB.equals(event)) {
            if (eventKey != null && eventKey.contains("qrscene_")) {
                String relation = eventKey.split("_")[1];
                logger.error("relation----" + relation);
                if (relation.contains("-")) {
                    String userid = relation.split("-")[0];
                    logger.error("userid----" + userid);
                    //下面处理用户关注成功自动注册用户
                    UserInfo userByWxId = userRepository.getUserByWxId(fromUserName);
                    if (userByWxId == null) {
                        logger.error("userByWxId is null----" + relation);
                        User wx = accountService.getUserInfo(fromUserName);
                        if (wx.getNickname() != null) {
                            logger.error("getUserInfo ----" + wx.getNickname());
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String time = simpleDateFormat.format(new Date());
                            UserInfo userInfo = new UserInfo();
                            userInfo.setGrade(commonRepository.findOne(40).getValue());
                            userInfo.setInvitation(userid);
                            userInfo.setImage_url(wx.getHeadimgurl());
                            userInfo.setGender(String.valueOf(wx.getSex()));
                            userInfo.setAddress(wx.getCity());
                            userInfo.setNickName(wx.getNickname());
                            userInfo.setPwd(MD5Util.encoderByMd5("123456"));
                            userInfo.setJifen("0");
                            userInfo.setOrderJifen("0");
                            userInfo.setIsInvitation(1);
                            userInfo.setPlatform("weixin");
                            userInfo.setCreateAt(time);
                            userInfo.setState("true");
                            userInfo.setOpenId(fromUserName);
                            UserInfo save = userJpaRepository.saveAndFlush(userInfo);
                            iUserService.checkRelationInvitations(userid, userInfo.getNickName());
                        }
                    }
                    //处理商品
                    String goodids = relation.split("-")[1];
                    logger.error("goodids----" + goodids);
                    String mian = Config.sendCustomer(fromUserName, "☞ 收到好友分享的免单商品", "快戳我领取吧", yuming.getValue() + "/pages/detail/goodsinfos?itemid=" + goodids, yuming.getValue() + "/free.png");
                    MessageAPI.messageCustomSend(accountTokenService.getWxToken(), mian);
                    String mycontent = Config.menuText(yuming.getValue(), one.getValue(), name.getValue());
                    //创建回复
                    XMLMessage xmlTextMessage = new XMLTextMessage(
                            fromUserName,
                            eventMessage.getToUserName(),
                            mycontent);
                    //回复
                    xmlTextMessage.outputStreamWrite(outputStream, wxBizMsgCrypt);
                }
            } else {
                String mian = Config.sendCustomer(fromUserName, "☞ 新人免单:万件商品免费领", "快戳我领取吧", yuming.getValue() + "/pages/index/mian", yuming.getValue() + "/free.png");
                MessageAPI.messageCustomSend(accountTokenService.getWxToken(), mian);
                String mycontent = Config.menuText(yuming.getValue(), one.getValue(), name.getValue());
                //创建回复
                XMLMessage xmlTextMessage = new XMLTextMessage(
                        fromUserName,
                        eventMessage.getToUserName(),
                        mycontent);
                //回复
                xmlTextMessage.outputStreamWrite(outputStream, wxBizMsgCrypt);
            }
        } else {
            if (StringUtils.isNotBlank(eventMessage.getContent())) {
                String content = eventMessage.getContent().replaceAll("\\s*", "");
                String contents = eventMessage.getContent();
                logger.error("receiver content is ----" + content);
                logger.error("receiver content is ----" + contents);
                logger.error("getToUserName" + eventMessage.getToUserName());
                logger.error("getFromUserName" + fromUserName);

//                String strWxBizMsgCrypt = JSON.toJSONString(wxBizMsgCrypt);
                UserInfo user = userRepository.getUserByWxId(fromUserName);
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setState(String.valueOf(7));
                messageInfo.setContent(content);
                messageInfo.setTitle("公众号消息");
                if (user != null) {
                    messageInfo.setUserName("成员：" + user.getNickName());
                    messageInfo.setUserId(String.valueOf(user.getId()));
                }
                messageInfo.setOpenId(eventMessage.getToUserName());
                messageInfo.setToUserName(eventMessage.getToUserName());
                messageInfo.setFromUserName(fromUserName);
//                messageInfo.setWxBizMsgCrypt(strWxBizMsgCrypt);
                iMessageService.saveBody(messageInfo);

                if (content.contains("https://item.m.jd.com/product/")) {
                    String id = content.substring(30, content.indexOf(".html"));
                    sendJd(yuming, outputStream, wxBizMsgCrypt, eventMessage, fromUserName, content, id);
                } else if (content.contains("https://wqitem.jd.com/item/view?")) {
                    int i = content.indexOf("sku=");
                    String id = content.substring(i + 4, content.indexOf("&"));
                    sendJd(yuming, outputStream, wxBizMsgCrypt, eventMessage, fromUserName, content, id);
                } else if (content.contains("https://mobile.yangkeduo.com/goods.html?goods_id=")) {
                    String id = content.substring(content.indexOf("goods_id=") + 9, content.indexOf("&"));
                    sendPdd(yuming, outputStream, wxBizMsgCrypt, eventMessage, fromUserName, content, id);
                } else if (content.contains("https://mobile.yangkeduo.com/goods2.html?")) {
                    String id = content.substring(content.indexOf("goods_id=") + 9, content.length());
                    sendPdd(yuming, outputStream, wxBizMsgCrypt, eventMessage, fromUserName, content, id);
                } else if (content.contains("vip.com")) {
                    Map<String, String> param = new HashMap<>();
                    param.put("apkey", commonRepository.findOne(30).getValue());
                    param.put("key", commonRepository.findOne(239).getValue());
                    param.put("source", Config.BASE_NAME);
                    param.put("content", content);
                    String body = HttpClientUtil.doGet("http://api.web.ecapi.cn/vip/changeCpsUrlToItem", param);
                    JSONObject jsonObject = JSONObject.parseObject(body);
                    String code = jsonObject.getString("code");
                    if ("200".equals(code)) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        JSONObject successMap = data.getJSONObject("successMap");
                        JSONObject jsonObject1 = successMap.getJSONObject(content);
                        String id = jsonObject1.getString("goodsId");
                        sendWph(yuming, outputStream, wxBizMsgCrypt, eventMessage, fromUserName, content, id);
                    }
                } else {
                    content=contents;
                    String item_id = getTwd(content);
                    if (StringUtils.isNotEmpty(item_id)) {
                        sendProduct(yuming, outputStream, wxBizMsgCrypt, eventMessage, fromUserName, content, item_id);
                    } else {
                        boolean flag = true;
                        String urls="https://v2.api.haodanku.com/dy_analyze_code";
                        Map<String,String> maps=new HashMap<>();
                        maps.put("apikey",commonRepository.findOne(238).getValue());
                        maps.put("content",content);
                        String stringJson = HttpClientUtil.doPost(urls, maps);
                        JSONObject jsonObjects = JSONObject.parseObject(stringJson);
                        String msg = jsonObjects.getString("msg");
                        if("SUCCESS".equals(msg)){
                            JSONObject data = jsonObjects.getJSONObject("data");
                            String id = data.getString("goods_id");
                            sendWph(yuming, outputStream, wxBizMsgCrypt, eventMessage, fromUserName, content, id);
                        }else{
                            Pattern pattern = Pattern.compile("https?://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]");
                            Matcher matcher = pattern.matcher(content);
                            if(matcher.find()){
                                String pddUrl = getPddUrl(matcher.group());
                                if(StringUtils.isNotEmpty(pddUrl)){
                                    JSONObject jsonObject = com.alibaba.fastjson.JSON.parseObject(pddUrl);
                                    JSONObject goods_zs_unit_generate_response = jsonObject.getJSONObject("goods_zs_unit_generate_response");
                                    if(goods_zs_unit_generate_response!=null){
                                        String url = goods_zs_unit_generate_response.getString("url");
                                        if (StringUtils.isNotEmpty(url)) {
                                            String id = url.substring(url.indexOf("goods_id=") + 9, url.indexOf("&"));
                                            if (StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(url)) {
                                                flag = false;
                                                sendPdd(yuming, outputStream, wxBizMsgCrypt, eventMessage, fromUserName, content, id);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (flag) {
                            //关键字回复
                            WordInfo one1 = wordRepository.findOne(content);
                            if (one1 != null) {
                                //创建回复
                                XMLMessage xmlTextMessage = new XMLTextMessage(
                                        fromUserName,
                                        eventMessage.getToUserName(),
                                        one1.getValue());
                                //回复
                                xmlTextMessage.outputStreamWrite(outputStream, wxBizMsgCrypt);
                            } else {
                                if (content.contains("yangkeduo.com")) {
                                    sendTwoSearch(outputStream, wxBizMsgCrypt, eventMessage, content);
                                } else if (content.contains("jd.com")) {
                                    sendTwoSearch(outputStream, wxBizMsgCrypt, eventMessage, content);
                                } else {
                                    sendSearch(outputStream, wxBizMsgCrypt, eventMessage, content);
                                }
                            }
                        }
                    }
                }
            }
        }

    }

    public String getTwd(String content) {
        try {
            String value = commonRepository.findOne(255).getValue();
            if("1".equals(value)){
                CommonInfo three = commonRepository.findOne(30);
                CommonInfo pid = commonRepository.findOne(9);
                //CommonInfo ze = commonRepository.findOne(90);
                CommonInfo tb = commonRepository.findOne(11);
            /*String pattern = ze.getValue();
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(content);
            String group = "";
            if (m.find()) {
                group = m.group();
                System.out.println("match: " + group);
            }
            System.out.println("End");*/
                String apkey = three.getValue();
                String tbname = tb.getValue();
                Pattern p1 = Pattern.compile("[\u4e00-\u9fa5]");
                Matcher m1 = p1.matcher(tb.getValue());
                if (m1.find()) {
                    tbname = URLEncoder.encode(tb.getValue(), "utf-8");
                }
                String word = URLEncoder.encode(content, "utf-8");

                String url = Config.MIAOYOUQUN_URL + "/taoke/doTpwdCovert?apkey=" + apkey + "&pid=" + pid.getValue() + "&content=" + word + "&tbname=" + tbname;

                String s = HttpClient.doGet(url);
                if (com.alibaba.fastjson.JSON.parseObject(s).getString("code").equals("200")) {
                    String data = com.alibaba.fastjson.JSON.parseObject(s).getString("data");
                    String item_id = com.alibaba.fastjson.JSON.parseObject(data).getString("item_id");
                    String goodsUrl=Config.MIAOYOUQUN_URL+"/taoke/getTkMaterialItem?keyword="+item_id+"&pid="+pid.getValue()+"&biz_scene_id=2&tbname="+tbname+"&apkey="+apkey;
                    String s1 = HttpClientUtil.doGet(goodsUrl);
                    JSONObject jsonObject = JSONObject.parseObject(s1);
                    String code = jsonObject.getString("code");
                    if("200".equals(code)){
                        JSONArray data1 = jsonObject.getJSONArray("data");
                        if(data1!=null && data1.size()>0){
                            JSONObject jsonObject1 = data1.getJSONObject(0);
                            return jsonObject1.getString("item_id");
                        }
                    }
                    return null;
                } else {
                    return null;
                }
            }else{
                /*String appId=commonRepository.findOne(253).getValue();
                String appSecret=commonRepository.findOne(254).getValue();
                String time = DateUtil.createTime();
                String str="https://v3.api.haodanku.com/rest";
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("method","analyze.taoword");
                jsonObject.put("app_id",appId);
                jsonObject.put("date",time);
                jsonObject.put("taoword",content);
                String sign="app_id"+appId+"date"+time+"methodanalyze.taowordtaoword"+content+appSecret;
                jsonObject.put("sign",MD5Util.md5Encrypt32Upper(sign));
                String s = HttpClientUtil.doPostJson(str, jsonObject.toJSONString());
                JSONObject jsonObject1 = JSONObject.parseObject(s);
                String code = jsonObject1.getString("code");
                if("200".equals(code)){
                    JSONObject data = jsonObject1.getJSONObject("data");
                    return data.getString("itemid");
                }*/
                String appId=commonRepository.findOne(253).getValue();
                String appSecret=commonRepository.findOne(254).getValue();
                String time = DateUtil.createTime();
                String str="https://v3.api.haodanku.com/rest";
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("method","analyze.clipboard");
                jsonObject.put("app_id",appId);
                jsonObject.put("date",time);
                jsonObject.put("content",content);
                jsonObject.put("is_change","0");
                String sign="app_id"+appId+"content"+content+"date"+time+"is_change0methodanalyze.clipboard"+appSecret;
                jsonObject.put("sign",MD5Util.md5Encrypt32Upper(sign));
                String s = HttpClientUtil.doPostJson(str, jsonObject.toJSONString());
                JSONObject jsonObject1 = JSONObject.parseObject(s);
                String code = jsonObject1.getString("code");
                if("200".equals(code)){
                    JSONObject data = jsonObject1.getJSONObject("data");
                    return data.getString("item_id");
                }
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }


    public String getPddUrl(String content) {
        CommonInfo clientId = commonRepository.findOne(23);
        CommonInfo clientSecret = commonRepository.findOne(24);
        CommonInfo pdd = commonRepository.findOne(26);
        UserInfo userInfos = userRepository.getUserByPdd(pdd.getValue());
        PopClient client = new PopHttpClient(clientId.getValue(), clientSecret.getValue());
        PddDdkGoodsZsUnitUrlGenRequest request = new PddDdkGoodsZsUnitUrlGenRequest();
        String s1 = "{\"uid\":\"" + userInfos.getRelationId() + "\"}";
        request.setPid(userInfos.getPdd());
        request.setCustomParameters(s1);
        request.setSourceUrl(content);
        PddDdkGoodsZsUnitUrlGenResponse response = null;
        try {
            response = client.syncInvoke(request);
            return JsonUtil.transferToJson(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private int sendPdd(CommonInfo yuming, ServletOutputStream outputStream, WXBizMsgCrypt wxBizMsgCrypt, EventMessage eventMessage, String fromUserName, String content, String id) {
        CommonInfo clientId = commonRepository.findOne(23);
        CommonInfo clientSecret = commonRepository.findOne(24);
        PopClient clients = new PopHttpClient(clientId.getValue() != null ? clientId.getValue() : Config.clientId, clientSecret.getValue() != null ? clientSecret.getValue() : Config.clientSecret);
        PddDdkGoodsSearchRequest requests = new PddDdkGoodsSearchRequest();
        requests.setKeyword(id);
        CommonInfo pdd = commonRepository.findOne(26);
        UserInfo userInfo = userRepository.getUserByPdd(pdd.getValue());
        String code = "{\"uid\":\"" + userInfo.getRelationId() + "\"}";
        requests.setPid(userInfo.getPdd());
        requests.setCustomParameters(code);
        requests.setWithCoupon(true);
        try {
            PddDdkGoodsSearchResponse pddDdkGoodsSearchResponse = clients.syncInvoke(requests);
            String goodsSign = pddDdkGoodsSearchResponse.getGoodsSearchResponse().getGoodsList().get(0).getGoodsSign();
            PopClient client = new PopHttpClient(clientId.getValue() != null ? clientId.getValue() : Config.clientId, clientSecret.getValue() != null ? clientSecret.getValue() : Config.clientSecret);
            PddDdkGoodsDetailRequest request = new PddDdkGoodsDetailRequest();
            request.setGoodsSign(goodsSign);
            PddDdkGoodsDetailResponse pddDdkGoodsDetailResponse = client.syncInvoke(request);
            PddDdkGoodsDetailResponse.GoodsDetailResponse goodsDetailResponse = pddDdkGoodsDetailResponse.getGoodsDetailResponse();
            List<PddDdkGoodsDetailResponse.GoodsDetailResponseGoodsDetailsItem> goodsDetails = goodsDetailResponse.getGoodsDetails();
            PddDdkGoodsDetailResponse.GoodsDetailResponseGoodsDetailsItem goodsDetailResponseGoodsDetailsItem = goodsDetails.get(0);
            CommodityCoupon commodityCoupon = new CommodityCoupon();
            commodityCoupon.setCouponmoney(AmountCalUtils.divide(Double.parseDouble(goodsDetailResponseGoodsDetailsItem.getCouponDiscount().toString()), 100).toString());
            Long money = goodsDetailResponseGoodsDetailsItem.getMinGroupPrice() - goodsDetailResponseGoodsDetailsItem.getCouponDiscount();
            commodityCoupon.setItemendprice(AmountCalUtils.divide(Double.parseDouble(money.toString()), 100).toString());
            commodityCoupon.setItemid(goodsDetailResponseGoodsDetailsItem.getGoodsId());
            commodityCoupon.setItempic(goodsDetailResponseGoodsDetailsItem.getGoodsImageUrl());
            commodityCoupon.setItemtitle(goodsDetailResponseGoodsDetailsItem.getGoodsName());
            //计算佣金  拼多多计算方式   （ minGroupPrice - couponDiscount ） *  0.01 * （ promotionRate * 0.001 ）
            Long minGroupPrice = goodsDetailResponseGoodsDetailsItem.getMinGroupPrice();
            Long couponDiscount = goodsDetailResponseGoodsDetailsItem.getCouponDiscount();
            Double promotionRate = Double.parseDouble(goodsDetailResponseGoodsDetailsItem.getPromotionRate().toString());
            minGroupPrice = minGroupPrice - couponDiscount;
            Double mul = AmountCalUtils.mul(promotionRate, 0.001);
            mul = AmountCalUtils.mul(mul, AmountCalUtils.mul(minGroupPrice, 0.01));

            DecimalFormat formater = new DecimalFormat();
            formater.setMaximumFractionDigits(2);
            formater.setGroupingSize(0);
            formater.setRoundingMode(RoundingMode.FLOOR);
            commodityCoupon.setTkmoney(formater.format(mul));

            UserInfo userByWxId = userRepository.getUserByWxId(fromUserName);
            String tkmoney = commodityCoupon.getTkmoney();
            DecimalFormat df = new DecimalFormat("#########.##");
            float d = Float.parseFloat(tkmoney);
            double b = 0.00;
            if(userByWxId!=null){
                b = d * Float.parseFloat(userByWxId.getGrade());
            }else{
                b = d * Float.parseFloat(commonRepository.findOne(41).getValue());
            }


            String s1 = df.format(b);
            CommonInfo one = commonRepository.findOne(4);
            String mian = Config.sendCustomer(fromUserName, commodityCoupon.getItemtitle(), "券后：" + commodityCoupon.getItemendprice() + "元\n优惠：" + commodityCoupon.getCouponmoney() + "元券\n返现：" + s1 + "元", yuming.getValue() + "/pages/detail/pdd?itemid=" + commodityCoupon.getItemid() + "&relation_id=" + one.getValue(), commodityCoupon.getItempic());
            MessageAPI.messageCustomSend(accountTokenService.getWxToken(), mian);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        sendTwoSearch(outputStream, wxBizMsgCrypt, eventMessage, content);
        return 0;
    }


    private int sendJd(CommonInfo yuming, ServletOutputStream outputStream, WXBizMsgCrypt wxBizMsgCrypt, EventMessage eventMessage, String fromUserName, String content, String id) {
        CommonInfo three = commonRepository.findOne(30);
        String apkey = Config.MIAOYOUQUN_Key;
        if (three != null) {
            apkey = three.getValue();
        }
        String url = Config.MIAOYOUQUN_URL + "/jingdong/getJdUnionItems?apkey=" + apkey + "&skuIds=" + id;
        String s = HttpClient.doGet(url);
        JSONObject body = JSON.parseObject(s);
        Integer code1 = body.getInteger("code");
        if (200 == code1) {
            JSONObject data = body.getJSONObject("data");
            JSONArray jsonArray = data.getJSONArray("list");
            if (jsonArray.size() > 0) {
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                CommodityCoupon commodityCoupon = new CommodityCoupon();
                JSONObject couponInfo = jsonObject.getJSONObject("couponInfo");
                JSONArray couponList = couponInfo.getJSONArray("couponList");
                if (couponList.size() > 0) {
                    String discount = couponList.getJSONObject(0).getString("discount");
                    commodityCoupon.setCouponmoney(discount);
                    JSONObject priceInfo = jsonObject.getJSONObject("priceInfo");
                    String lowestCouponPrice = priceInfo.getString("lowestCouponPrice");
                    commodityCoupon.setItemendprice(lowestCouponPrice);
                } else {
                    commodityCoupon.setCouponmoney("0");
                    JSONObject priceInfo = jsonObject.getJSONObject("priceInfo");
                    String price = priceInfo.getString("price");
                    commodityCoupon.setItemendprice(price);
                }
                commodityCoupon.setItemid(jsonObject.getLong("skuId"));
                JSONObject imageInfo = jsonObject.getJSONObject("imageInfo");
                JSONArray imageList = imageInfo.getJSONArray("imageList");
                String url1 = imageList.getJSONObject(0).getString("url");
                commodityCoupon.setItempic(url1);
                commodityCoupon.setItemtitle(jsonObject.getString("skuName"));
                //计算佣金  京东 直接取值 不用计算
                JSONObject commissionInfo = jsonObject.getJSONObject("commissionInfo");
                String couponCommission = commissionInfo.getString("couponCommission");
                if (StringUtils.isNotBlank(couponCommission)) {
                    commodityCoupon.setTkmoney(couponCommission);
                } else {
                    commodityCoupon.setTkmoney("0.00");
                }
                try {

                    UserInfo userByWxId = userRepository.getUserByWxId(fromUserName);
                    String tkmoney = couponCommission;
                    DecimalFormat df = new DecimalFormat("#########.##");
                    double b = 0;
                    if (StringUtils.isNotBlank(tkmoney)) {
                        float d = Float.parseFloat(tkmoney);
                        if(userByWxId!=null){
                            b = d * Float.parseFloat(userByWxId.getGrade());
                        }else{
                            b = d * Float.parseFloat(commonRepository.findOne(41).getValue());
                        }
                    }
                    String s1 = df.format(b);
                    CommonInfo one = commonRepository.findOne(4);
                    String mian = Config.sendCustomer(fromUserName, commodityCoupon.getItemtitle(), "券后：" + commodityCoupon.getItemendprice() + "元\n优惠：" + commodityCoupon.getCouponmoney() + "元券\n返现：" + s1 + "元", yuming.getValue() + "/pages/detail/jd?itemid=" + commodityCoupon.getItemid() + "&relation_id=" + one.getValue(), commodityCoupon.getItempic());
                    MessageAPI.messageCustomSend(accountTokenService.getWxToken(), mian);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    sendTwoSearch(outputStream, wxBizMsgCrypt, eventMessage, content);
                }
                return 1;
            }
        }
        sendTwoSearch(outputStream, wxBizMsgCrypt, eventMessage, content);
        return 0;
    }

    private int sendWph(CommonInfo yuming, ServletOutputStream outputStream, WXBizMsgCrypt wxBizMsgCrypt, EventMessage eventMessage, String fromUserName, String content, String id) {
        CommonInfo appkey = commonRepository.findOne(30);
        CommonInfo key = commonRepository.findOne(239);
        Map<String, String> map = new HashMap<>();
        map.put("apkey", appkey.getValue());
        map.put("key", key.getValue());
        map.put("goodsIdList", id);
        String body = HttpClientUtil.doGet("http://api.web.ecapi.cn/vip/getGoodsInfo", map);
        JSONObject jsonObject = JSONObject.parseObject(body);
        String code = jsonObject.getString("code");
        if ("200".equals(code)) {
            JSONArray data = jsonObject.getJSONArray("data");
            if (data.size() > 0) {
                JSONObject jsonObject1 = data.getJSONObject(0);
                String goodsName = jsonObject1.getString("goodsName");
                String vipPrice = jsonObject1.getString("vipPrice");
                String marketPrice = jsonObject1.getString("marketPrice");
                JSONArray goodsCarouselPictures = jsonObject1.getJSONArray("goodsCarouselPictures");
                String image = goodsCarouselPictures.getString(0);
                BigDecimal bigDecimal = new BigDecimal(marketPrice).subtract(new BigDecimal(vipPrice)).setScale(2, BigDecimal.ROUND_UP);

                UserInfo userByWxId = userRepository.getUserByWxId(fromUserName);
                String tkmoney = jsonObject1.getString("commission");
                DecimalFormat df = new DecimalFormat("#########.##");
                double b = 0;
                if (StringUtils.isNotBlank(tkmoney)) {
                    float d = Float.parseFloat(tkmoney);
                    if(userByWxId!=null){
                        b = d * Float.parseFloat(userByWxId.getGrade());
                    }else{
                        b = d * Float.parseFloat(commonRepository.findOne(41).getValue());
                    }
                }
                String s1 = df.format(b);

                CommonInfo one = commonRepository.findOne(4);
                String mian = Config.sendCustomer(fromUserName, goodsName, "券后：" + vipPrice + "元\n优惠：" + bigDecimal + "元券\n返现：" + s1 + "元", yuming.getValue() + "/pages/detail/wph?itemid=" + id + "&relation_id=" + one.getValue(), image);
                MessageAPI.messageCustomSend(accountTokenService.getWxToken(), mian);
            }
        }else{
            sendTwoSearch(outputStream, wxBizMsgCrypt, eventMessage, content);
        }
        return 0;
    }


    private int sendDy(CommonInfo yuming, ServletOutputStream outputStream, WXBizMsgCrypt wxBizMsgCrypt, EventMessage eventMessage, String fromUserName, String content, String id) {
        CommonInfo appkey = commonRepository.findOne(238);
        Map<String,String> map=new HashMap<>();
        map.put("apikey",appkey.getValue());
        map.put("itemid",id);
        String body = HttpClientUtil.doGet("https://v2.api.haodanku.com/dy_detail", map);
        JSONObject jsonObject = JSONObject.parseObject(body);
        JSONArray data = jsonObject.getJSONArray("data");
        if (data.size() > 0) {
            JSONObject jsonObject1 = data.getJSONObject(0);
            String goodsName = jsonObject1.getString("product_title");
            String vipPrice = jsonObject1.getString("price");
            String marketPrice = jsonObject1.getString("price");
            JSONArray goodsCarouselPictures = jsonObject1.getJSONArray("douyin_images");
            String image = goodsCarouselPictures.getString(0);
            BigDecimal bigDecimal = BigDecimal.ZERO;
            UserInfo userByWxId = userRepository.getUserByWxId(fromUserName);
            String tkmoney = jsonObject1.getString("dymoney");
            DecimalFormat df = new DecimalFormat("#########.##");
            double b = 0;
            if (StringUtils.isNotBlank(tkmoney)) {
                float d = Float.parseFloat(tkmoney);
                if(userByWxId!=null){
                    b = d * Float.parseFloat(userByWxId.getGrade());
                }else{
                    b = d * Float.parseFloat(commonRepository.findOne(41).getValue());
                }
            }
            String s1 = df.format(b);

            CommonInfo one = commonRepository.findOne(4);
            String mian = Config.sendCustomer(fromUserName, goodsName, "券后：" + vipPrice + "元\n优惠：" + bigDecimal + "元券\n返现：" + s1 + "元", yuming.getValue() + "/pages/detail/dy?itemid=" + id + "&relation_id=" + one.getValue(), image);
            MessageAPI.messageCustomSend(accountTokenService.getWxToken(), mian);
        }
        return 0;
    }


    private void sendProduct(CommonInfo yuming, ServletOutputStream outputStream, WXBizMsgCrypt wxBizMsgCrypt, EventMessage eventMessage, String fromUserName, String content, String id) {
        String s = HttpClient.doGet(yuming.getValue() + "/api/item_detail/apikey/maxd/itemid/" + id);
        Product product = JSON.parseObject(s, new TypeReference<Product>() {
        });
        if (product.getCode() == 1) {
            try {
                UserInfo userByWxId = userRepository.getUserByWxId(fromUserName);
                String tkmoney = product.getData().getTkmoney();
                DecimalFormat df = new DecimalFormat("#########.##");
                float d = Float.parseFloat(tkmoney);
                double b = 0.00;
                if(userByWxId!=null){
                    b = d * Float.parseFloat(userByWxId.getGrade());
                }else{
                    b = d * Float.parseFloat(commonRepository.findOne(41).getValue());
                }
                String s1 = df.format(b);
                CommonInfo one = commonRepository.findOne(4);
                String mian = Config.sendCustomer(fromUserName, product.getData().getItemtitle(), "券后：" + product.getData().getItemendprice() + "元\n优惠：" + product.getData().getCouponmoney() + "元券\n返现：" + s1 + "元", yuming.getValue() + "/pages/detail/goodsinfo?itemid=" + product.getData().getItemid() + "&relation_id=" + one.getValue(), product.getData().getItempic());
                MessageAPI.messageCustomSend(accountTokenService.getWxToken(), mian);
            } catch (NumberFormatException e) {
                e.printStackTrace();
                sendSearch(outputStream, wxBizMsgCrypt, eventMessage, content);
            }
        } else {
            sendSearch(outputStream, wxBizMsgCrypt, eventMessage, content);
        }
    }

    private void sendSearch(ServletOutputStream outputStream, WXBizMsgCrypt wxBizMsgCrypt, EventMessage eventMessage, String content) {
        //后台服务域名配置
        CommonInfo yuming = commonRepository.findOne(19);
        //注册邀请码
        CommonInfo yaoqingma = commonRepository.findOne(4);
        User wx = accountService.getUserInfo(eventMessage.getFromUserName());
        if (wx.getNickname() != null) {
            String mycontent1 = Config.menuText1(wx.getNickname(), yuming.getValue() + "/pages/search/search?keywords=" + content + "&invitation=" + yaoqingma.getValue());
            //创建回复
            XMLMessage xmlTextMessage = new XMLTextMessage(
                    eventMessage.getFromUserName(),
                    eventMessage.getToUserName(),
                    mycontent1);
            //回复
            xmlTextMessage.outputStreamWrite(outputStream, wxBizMsgCrypt);
        } else {
            String mycontent1 = Config.menuText1("亲", yuming.getValue() + "/pages/search/search?keywords=" + content + "&invitation=" + yaoqingma.getValue());
            //创建回复
            XMLMessage xmlTextMessage = new XMLTextMessage(
                    eventMessage.getFromUserName(),
                    eventMessage.getToUserName(),
                    mycontent1);
            //回复
            xmlTextMessage.outputStreamWrite(outputStream, wxBizMsgCrypt);
        }
    }

    private void sendTwoSearch(ServletOutputStream outputStream, WXBizMsgCrypt wxBizMsgCrypt, EventMessage eventMessage, String content) {
        String mycontent1 = "未能通过链接找到您需要的商品\n" +
                "-------------------------------\n" +
                "☞ 请发送【商品标题】至公众号查询 >>\n" +
                "-------------------------------\n" +
                "人工客服，请点右下角";
        //创建回复
        XMLMessage xmlTextMessage = new XMLTextMessage(
                eventMessage.getFromUserName(),
                eventMessage.getToUserName(),
                mycontent1);
        //回复
        xmlTextMessage.outputStreamWrite(outputStream, wxBizMsgCrypt);
    }

    /**
     * 数据流输出
     */
    private void outputStreamWrite(OutputStream outputStream, String text) {
        try {
            outputStream.write(text.getBytes("utf-8"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * token
     * 获取token
     *
     * @return openid
     */
    @GetMapping("/token")
    @ApiOperation("管理平台获取token")
    public String getToken() {
        return accountTokenService.getWxToken();
    }


//    @GetMapping("sendMsg")
//    @ApiOperation("消息推送")
//    public void sendMessage(@RequestParam String title, @RequestParam String content,@RequestParam String client) {
//        pushToSingle(title, content,client);
//    }


    /**
     * token
     * 获取菜单
     *
     * @return openid
     */
    @GetMapping("/menu")
    @ApiOperation("管理平台获取菜单")
    public weixin.popular.bean.menu.Menu getMenu() {
        return MenuAPI.menuGet(accountTokenService.getWxToken());
    }

    /**
     * token
     * 创建菜单
     *
     * @return openid
     */
    @PostMapping("/create")
    @ApiOperation("管理平台创建菜单")
    public Result createMenu(@RequestBody JSONObject jsonObject) {
        String s1 = HttpClientUtil.doPostJson("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accountTokenService.getWxToken(), jsonObject.toString());
        return ResultUtil.success(JSONObject.parseObject(s1));
    }

    /**
     * 检查是否关注公众号
     *
     * @param openid openid
     * @return boolean
     */
    @GetMapping("/follow/{openId:.+}")
    @ApiOperation("用户端检查是否关注公众号")
    public boolean checkIsFollow(@PathVariable("openId") String openid) {
//        log.info("判断用户是否关注：openid={}", openid);
        return accountService.checkIsFollow(openid);
    }

    /**
     * 获取openid
     * 获取用户信息
     *
     * @param openId openId
     * @return openid
     */
    @GetMapping("/userInfo/{openId:.+}")
    @ApiOperation("用户端通过openid获取微信用户信息")
    public User getUserInfo(@PathVariable("openId") String openId) {
        return accountService.getUserInfo(openId);
    }

    /**
     * 获取签名
     * 监测js签名
     *
     * @param url request的url
     * @return String
     */
    @GetMapping("/js/sign")
    @ApiOperation("用户端获取js签名")
    public String getJSSign(@RequestParam String url) {
        return accountService.getJSSign(url);
    }

    @GetMapping("/users")
    @ApiOperation("获取关注公众号用户列表")
    public FollowResult getUserList() {
        return UserAPI.userGet(accountTokenService.getWxToken(), null);
    }

    @GetMapping("/getUserTotal")
    @ApiOperation("获取关注公众号用户总数")
    public Result getUserTotal() {
        return ResultUtil.success(UserAPI.userGet(accountTokenService.getWxToken(), null).getTotal());
    }

//    @GetMapping("/saveUser")
//    public Result saveUser() {
//        FollowResult followResult = UserAPI.userGet(accountTokenService.getWxToken(), null);
//        String[] openid = followResult.getData().getOpenid();
//        for (String i : openid) {
//            Result result = iUserService.loginByOpenId(i);
//        }
//        return ResultUtil.success();
//    }

}
